<?php

namespace App\Http\Controllers\Backstage;

use App\Http\Controllers\Backstage\BCommonController;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Input;
use App\Models\CommonModel;
use App\Models\BackstageModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Libary\Captcha\Code;
use Illuminate\Support\Facades\Validator;
class AdvertController extends BCommonController
{

    protected $redirectTo = '/backstage/advert/index';
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $list = CommonModel::getList('advert');
        return view('backstage/advert/index',compact('list'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function add()
    {
        return view('backstage/advert/add');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function doadd(Request $request)
    {
        // dd($request->except('_token'));
        if( $request->isMethod('POST') ){
            $post = $request->except('_token');

            $jump_urls = $post['jump_url'];
            $infos = $post['info'];
            if(empty($post['name'])) return json_encode(['status' => 0, 'message'=>'广告名称不能为空']);
            if(empty($post['type'])) return json_encode(['status' => 0, 'message'=>'广告类型不能为空！']);
            if(empty($post['start_time'])) return json_encode(['status' => 0, 'message'=>'开始时间不能为空']);
            $count = CommonModel::getCount('advert',['type'=>trim($post['type'])]);
            if($count>0) return json_encode(['status' => 0, 'message'=>'广告名称已经存在，请更换名称后重新提交']);
            $data['name'] = trim($data['name']);
            $data['type'] = trim($data['type']);
            $data['start_time'] = strtotime($data['start_time']);
            $data['end_time'] = strtotime($data['end_time']);
            $data['desc'] =trim($data['desc']);
            $data['add_time'] = time();
            $newid = CommonModel::addDataGetId('advert',$data);
            if(!$newid){
                $arrJson = array('status' => 0, 'message'=>'广告添加失败');
            }
            $files = $request->file('img_url');
            $bool = false;
            // 文件是否上傳成功
            if($files!=null && !empty($newid)){
                foreach($files as $key=>$file){
                    if ($file->isValid()){
                        // 獲取文件相關信息
                        $originalName = $file->getClientOriginalName(); // 文件原名
                        $ext = $file->getClientOriginalExtension();     // 擴展名

                        $realPath = $file->getRealPath();   //臨時文件的絕對路徑
                        $type = $file->getClientMimeType();     // image/jpeg
                        // 上傳文件
                        $filename = date('YmdHis') . '-' . uniqid() . '.' . $ext;
                        // 将图片URL保存到数据库
                        $image['ad_id'] = $newid;
                        $image['info'] = $infos[$key];
                        $image['jump_url'] = $jump_urls[$key];
                        $image['img_url'] = '/uploads/advert/'.trim($post['name']).'/'.$filename;
                        $image['sort_order'] = $key;
                        $image['add_time'] = time();
                        $res = CommonModel::addData('advert_img',$image);
                        // 使用我們新建的uploads本地存儲空間（目錄）
                        $bool = Storage::disk('uploads')->put($filename, file_get_contents($realPath));
                        // if($bool!=true){
                        //     $arrJson = array('status' => 0, 'message'=>'圖片上傳失敗');
                        //     return json_encode($arrJson);
                        // }
                    }
                }
            }
            
            $arrJson = array('status' => 1, 'message'=>'广告添加成功','jumpUrl'=>$this->redirectTo);
            return json_encode($arrJson);
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data = CommonModel::getOne('advert',['id'=>$id]);
        $imgs = DB::table('advert_img')->where('ad_id','=',$id)->orderBy('sort_order','asc')->get();
        // dd($imgs);
        return view('backstage/advert/edit',['data'=>$data,'imgs'=>$imgs]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function doedit(Request $request)
    {
        // dd($request->except('_token'));
        if( $request->isMethod('PUT') ){
            $post=$request->except('_token');
            $id = intval($post['id']);

            $img_ids = $post['img_id'];
            $jump_urls = $post['jump_url'];
            $infos = $post['info'];
            if(empty($post['name'])) return json_encode(['status' => 0, 'message'=>'广告名称不能为空']);
            if(empty($post['type'])) return json_encode(['status' => 0, 'message'=>'广告类型不能为空！']);
            if(empty($post['start_time'])) return json_encode(['status' => 0, 'message'=>'开始时间不能为空']);
            $count = DB::table('advert')->where('type','=',trim($post['type']))->where('id','<>',$id)->count();
            if($count>0) return json_encode(['status' => 0, 'message'=>'广告名称已经存在，请更换名称后重新提交']);
            $i = 0;
            $files = $request->file('img_url');
            $flag = false;
            foreach ($img_ids as $key => $value) {
                if($value>0){
                    CommonModel::updateData('advert_img',['id'=>$value],['sort_order',$key]);
                }else{
                    if($files!=null){
                        if ($files[$i]->isValid()){
                            // 獲取文件相關信息
                            $originalName = $files[$i]->getClientOriginalName(); // 文件原名
                            $ext = $files[$i]->getClientOriginalExtension();     // 擴展名

                            $realPath = $files[$i]->getRealPath();   //臨時文件的絕對路徑
                            $type = $files[$i]->getClientMimeType();     // image/jpeg
                            // 上傳文件
                            $filename = date('YmdHis') . '-' . uniqid() . '.' . $ext;
                            // 将图片URL保存到数据库
                            $image['ad_id'] = $id;
                            $image['info'] = $infos[$key];
                            $image['jump_url'] = $jump_urls[$key];
                            $image['img_url'] = '/uploads/advert/'.trim($post['name']).'/'.$filename;
                            $image['sort_order'] = $key;
                            $image['add_time'] = time();
                            $res = CommonModel::addData('advert_img',$image);
                            // 使用我們新建的uploads本地存儲空間（目錄）
                            $bool = Storage::disk('uploads')->put($filename, file_get_contents($realPath));
                            if($bool==true){
                                $flag = true;
                            }
                            // if($bool!=true){
                            //     $arrJson = array('status' => 0, 'message'=>'圖片上傳失敗');
                            //     return json_encode($arrJson);
                            // }
                        }
                        $i++;
                    }
                }
            }
            $data['name'] = trim($data['name']);
            $data['type'] = trim($data['type']);
            $data['start_time'] = strtotime($data['start_time']);
            $data['end_time'] = strtotime($data['end_time']);
            $data['desc'] =trim($data['desc']);
            $save = CommonModel::updateData('advert',['id'=>$id],$data);
            if($save || $flag){
                $arrJson = array('status' => 1, 'message'=>'广告修改成功','jumpUrl'=>$this->redirectTo);
            }else{
                $arrJson = array('status' => 0, 'message'=>'广告修改失败');
            }
            return json_encode($arrJson);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    // 刪除圖片并且改變狀態
    public function delimg($id){
        $idstr=$request->input('idstr');
        if($id != ''){
            $res =CommonModel::delData('advert_img',['id'=>$idarr[0]]);
            if($res){
                $info = CommonModel::getOne('advert_img',['id'=>$id]);
                if( !empty($info->img_url) || !file_exists($info->img_url) ){
                    @unlink(public_path() . $info->img_url);
                }
                return response()->json(array('status' => 1,'message'=>'刪除成功'));
            }else{
                return response()->json(array('status' => 0,'message'=>'刪除失敗'));
            }
        }
    }
    




}
